package com.lib.common.interceptor;

import com.lib.common.properties.JwtProperties;
import com.lib.common.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class TokenUserInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;
    /*
        这只是定义一个拦截器，还需要注入一个在server.config里面
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截器开始处理请求: {}", request.getRequestURI());
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        //1:获取请求路径
        String requestURI = request.getRequestURI();
        //2:判断是否是登录请求
        if (requestURI.contains("/user/login")){
            log.info("登录请求，放行");
            return true;//返回值为true就是放行了
        }
        //3：获取请求头的token
        String token = request.getHeader(jwtProperties.getUserTokenName());
        //4:判断token是否存在
        if (token == null || token.isEmpty()){
            log.info("token不存在");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);//应为token不存在响应状态码401
            return false;
        }
        //5：解析token，判断是否合法 -->  校验失败返回状态码401
        try {
            JwtUtils.parseToken(jwtProperties.getUserSecretKey(),token);
        } catch (Exception e) {
            log.info("非法令牌响应401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        //6：令牌合法，放行
        return true;
    }
}
